package com.slz3.business.module.messageManagement.mesCreate.service;

import com.slz3.business.frame.enums.ValidFlag;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.steward.PageableSteward;
import com.slz3.business.module.messageManagement.mesCreate.domain.MesCreate;
import com.slz3.business.module.messageManagement.mesCreate.domain.MesCreateFactory;
import com.slz3.business.module.messageManagement.mesCreate.steward.MesCreateSpecification;
import com.slz3.business.module.messageManagement.mesType.domain.MesType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MesCreateServiceImpl implements MesCreateService {
    @Override
    public MesCreate save(MesCreate mesCreate) {
        return Repositorys.mesCreate.save(MesCreateFactory.initBaseFields(mesCreate));
    }
    @Override
    public Page<MesCreate> page(MultiValueMap<String, String> params) {
        Page<MesCreate> mesCreatePage = Repositorys.mesCreate.findAll(
                MesCreateSpecification.findJoin(params), PageableSteward.extract(params)
        );
        Map<UUID, MesType> mesTypeMap = Repositorys.mesType.findAll().stream().collect(Collectors.toMap(MesType::getUuid, Function.identity()));

        mesCreatePage.stream().forEach(item -> item.setMesType(mesTypeMap.get(item.getSerActivityType())));
        return mesCreatePage;
    }


    @Override
    public MesCreate modify(MesCreate mesCreateNew) {
        return Repositorys.mesCreate.saveAndFlush(MesCreateFactory.initBaseFields(mesCreateNew));
    }

    @Override
    public Optional<MesCreate> single(UUID uuid) {
        return Repositorys.mesCreate.findById(uuid);
    }

    @Override
    public List<MesCreate> findAllByUuids(Iterable<UUID> uuids) {
        return Repositorys.mesCreate.findAllById(uuids);
    }

    @Override
    public List<MesCreate> delete(List<MesCreate> mesCreateList) {
        mesCreateList.stream().forEach(item -> {
            item.setValidFlag(ValidFlag.DEL);
            MesCreateFactory.initBaseFields(item);
        });
        return Services.mesCreateTransactional.batchModify(mesCreateList);
    }

}
